<?php

namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\ForbiddenHttpException;
use yii\grid\GridView;
use yii\helpers\Html;
use backend\models\CrowdItemSearch;
use yii\base\Object;
use backend\models\CrowdItem;
use backend\models\ItemPreview;
use yii\helpers\Url;
use backend\models\CrowdItemPrice;
use backend\models\BaseSysPreview;
use backend\models\UploadForm;
use backend\models\Image;
use backend\models\SysItem;
use yii\web\UploadedFile;
use frontend\models\PayTrade;
use backend\models\LogPay;
use backend\models\LogRefund;
use backend\models\PayRebateUsertake;
use MakemoneyApi;
use backend\models\PayLogistics;
    include_once "../../vendor/alipay/pagepay/makemoneyApi.php";
/**
 * 众筹 控制器
 * @author suiyue
 *
 */
class CrowdController extends BaseController
{
	/**
	 * (non-PHPdoc)行为
	 * @see \yii\base\Component::behaviors()
	 */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                		'delteprice'=>['post']
                ],
            ],
        ];
    }
    /**
     * (non-PHPdoc)前置函数
     * @see \yii\web\Controller::beforeAction()
     */
    public function beforeAction($action)
    {
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	$action_list = array(
    			'index',
    			'update',
    			'view',
    			'delete',
    			'create',
    			'upload',
    			'ggidlist',
    			'gmlist',
    			'getplist',
    			'fmgetsize',
    			'fgetsite',
    			'mgetsize' ,
    			'delteprice',
    			'getprice',
    			'checkprice',
    			'additemprice',
    			'updateprice',
    			'priceview',
    	       'addprice',
    	       'getpreviewid',
    	        'refund',
    	       'check-refund',
    	    'crowd-refund','logrefund'
    	    
    	);
    	 $access=$this->checkAccess($action_list,$action);//判断操作的action是否在actionlist里面
    	 $this->beforeOp('crowd', $access);//身份识别 权限验证  action验证
    	 return true;
    }
	/**
	 * 列表
	 */
    public function actionIndex()
    {
    	$searchModel = new CrowdItemSearch();
    	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    	return $this->render('index', [
    			'searchModel' => $searchModel,
    			'dataProvider' => $dataProvider,
    	]);
    }
    /**
     * 众筹退款列表
     */
    public function actionLogrefund(){
        $searchModel = new CrowdItemSearch();
        $dataProvider = $searchModel->logrefundsearch(Yii::$app->request->queryParams);
        return $this->render('logrefund_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * 创建 
     */
    public function actionCreate(){
    	$model = new CrowdItem();
    	if ($model->load(Yii::$app->request->post())&&$model->validate()) {
    	        //图片上传
    	        $Uploadmodel = new UploadForm();
    	        $Uploadmodel->scenario = 'no_need_file_name';
    	        $Uploadmodel->image_upload = UploadedFile::getInstance($model, 'img_crowd_id');
    	        if ($Uploadmodel->image_upload && $Uploadmodel->validate()) {
    	            $item_id=$model->item_id;
    	           /*  if(intval($item_id)>0){
    	                $sysitem=SysItem::findOne($item_id);
    	                $classId=$sysitem['class_id'];
    	            }else{
    	                $classId=$item_id;
    	            } */
    	            $arr = Image::save_image_to_files($Uploadmodel,195,'众筹图片','item_default_image_thumb','item_default_image_small');
    	            $model->img_crowd_id = $arr['img_url_id'];
    	        }
    			$post=Yii::$app->request->post();
    			$type_str='';
    			if(key_exists("user_types", $post['CrowdItem'])){
    			    $user_types=$post['CrowdItem']['user_types'];
    			    $type_str=$model->getUserStrByArray($user_types);
    			}
    			$model->user_types=$type_str;
    			$model->start_time=strtotime($model->start_time);
    			$model->end_time=strtotime($model->end_time);
    		 	$model->save();
     		 	return $this->redirect(['view', 'id' => $model->id]);
    	} else {
    	    $model->start_time=date("Y-m-d H:i:s");
    	    $model->end_time=date("Y-m-d H:i:s");
    		return $this->render('create', [
    				'model' => $model,
    		]);
    	}
    }
    /**
     * 修改
     */
    public function actionUpdate($id){
    		$model =$this->findModel($id);
    		$old_img_crowd_id=$model->img_crowd_id;
    		$crowdItem=new CrowdItem();
    		$old_itemid=intval($model->item_id);
    	if ($model->load(Yii::$app->request->post())) {
    	    
    	  
    	    if($model->img_crowd_id==0){
    	        $model->img_crowd_id=$old_img_crowd_id;
    	    }
    	    
    	    if($model->validate()){
    	        
    	        //图片上传
    	        $Uploadmodel = new UploadForm();
    	        $Uploadmodel->scenario = 'no_need_file_name';
    	        $Uploadmodel->image_upload = UploadedFile::getInstance($model, 'img_crowd_id');
    	        if ($Uploadmodel->image_upload && $Uploadmodel->validate()) {
    	            $item_id=$model->item_id;
    	           /*  if(intval($item_id)>0){
    	                $sysitem=SysItem::findOne($item_id);
    	                $classId=$sysitem['class_id'];
    	            }else{
    	                $classId=$item_id;
    	            } */
    	            $arr = Image::save_image_to_files($Uploadmodel,195,'众筹图片','item_default_image_thumb','item_default_image_small');
    	            $model->img_crowd_id = $arr['img_url_id'];
    	          
    	        }
    	        
    	        $new_itemid= intval($model->item_id);
    	        $model->start_time=strtotime($model->start_time);
    	        $model->end_time=strtotime($model->end_time);
    	        $post=Yii::$app->request->post();
    	        $type_str='';
    	        if(key_exists("user_types", $post['CrowdItem'])){
    	            $user_types=$post['CrowdItem']['user_types'];
    	            $type_str=$crowdItem->getUserStrByArray($user_types);
    	        }
    	        $model->user_types=$type_str;
    	        $model->save();
    	        if($old_itemid!=$new_itemid){
    	            //修改了单品的话，删除原来的 规格
    	            CrowdItemPrice::deleteAll("crowd_id=:crowd_id",array(":crowd_id"=>$model->id));
    	        }
    	        return $this->redirect(['view', 'id' => $model->id]);
    	    }else{
    	        $model =$this->findModel($id);
    	        $url= Url::to(['crowd/update',"id"=>$id]);
    	        echo "<script>alert('单品不存在');</script><script> 
                        window.location.href='$url'; 
                        </script>";
    	    }
    	} else {
    		if($model->start_time==""){
    			$model->start_time=date("Y-m-d H:i:s");
    		}else{
    			$model->start_time=date("Y-m-d H:i:s",$model->start_time);
    		}
    		if($model->end_time==""){
    			$model->end_time=date("Y-m-d H:i:s");
    		}else{
    			$model->end_time=date("Y-m-d H:i:s",$model->end_time);
    		}
    		//规格
    		$crowItemPriceModel=new CrowdItemPrice();
    		$Crowd=CrowdItem::findOne($id);
    		$item_id=$Crowd->item_id;
    		$crowpriceList=$crowItemPriceModel->getPriceByCrowdid($id);
    		$user_type=$model->user_types;
    		if($user_type==""){
    		    $model->user_types=[1=>'注册用户',3=>'认证VIP会员',4=>'装饰公司',5=>'城市运营商',6=>'协会',7=>'服务商',8=>'内部员工'];
    		}else{
    		    $model->user_types=explode(",", $user_type);
    		}
    		return $this->render('update', [
    				'model' => $model,
    				'dataProvider' =>$crowpriceList,
    				'searchModel'=>$crowItemPriceModel,
    				'crowId' => $id,
    				'item_id'=>$item_id
    		]);
    	}
    }
    /**
     * 规格修改
     */
    public function actionGetplist($id){
    	$crowItemPriceModel=new CrowdItemPrice();
    	$Crowd=CrowdItem::findOne($id);
    	$item_id=$Crowd->item_id;
    	$crowpriceList=$crowItemPriceModel->getPriceByCrowdid($id);
    	return $this->render('crowprice', [
    			'dataProvider_crowprice' => $crowpriceList,
    			'searchModel_crowprice'=>$crowItemPriceModel,
    			'crowId' => $id,
    			'item_id'=>$item_id
    	]);
    }
    /**
     * 删除规格
     */
    public function actionDelteprice($id){
    		$crowd_prcie=$this->findPriceModel($id);
    		$crowd_id=$crowd_prcie['crowd_id'];
    		$this->findPriceModel($id)->delete();
    		return $this->redirect(['update',"id"=>$crowd_id]);
    }
    /**
     * 点击添加规格， 根据item_id获取面料 以及材质
     */
    public function actionGgidlist(){
    	$crowdItemModel=new CrowdItem();
    	$post=Yii::$app->request->post();
    	$item_id=intval($post['item_id']);  
    	 if($item_id==0){
    	 	echo "<div>暂无</div>";exit();
    	 }
    	 //$item_id=2852;
    	$html="<div class='fm_list'>
    			<div class='fabirc'>";
    	//先判断这个单品是否存在组合 Preview   
    	$previewCount=$crowdItemModel->getPreviewByItem($item_id);
    	if(intval($previewCount)>0){
    	    $f_list=$crowdItemModel->getFabricByItem($item_id,0);
    	    //如果存在面料，材质跟着面料进行关联显示
    	    if(count($f_list)>0){
    	        //判断是否存在材质，如果不存在材质，直接控制规格
    	        $m_list=$crowdItemModel->getMaterialByItem($item_id,0);
    	        if(count($m_list)>0){//存在材质 显示材质，根据材质显示尺寸
    	            foreach($f_list as $fari){
    	                $html.=$fari['name']." &nbsp;&nbsp;
    				<input type='radio' name='CrowdItem[fid]' value='".$fari['fid']."' onchange='fabricChange(this)'>";
    	                $html.="<img  src='".$fari['url']."' width=50px;/>";
    	                $html.="&nbsp;&nbsp;&nbsp;&nbsp;";
    	            }
    	            $html.="
   			 </div>";
    	            $html.="<div class='mabir'> </div>
    					<div class='size'> </div>
    		 ";
    	        }else{//没有材质，面料选择了要控制材质  直
    	            //根据item_id 面料  获取尺寸 如果sys_item_prices没有尺寸 还需要去sys_item_size查找尺寸
    	            foreach($f_list as $fari){
    	                $html.=$fari['name']." &nbsp;&nbsp;
    				<input type='radio' name='CrowdItem[fid]' value='".$fari['fid']."' onchange='f_getSize(this)'>";
    	                $html.="<img  src='".$fari['url']."' width=50px;/>";
    	                $html.="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    	            }
    	            $html.="
   			 </div>";
    	            $html.="<div class='mabir'>  <h6> 暂无材质</h6></div>";
    	            $html.="<div class='size'> </div>";
    	            $html.="
    			 ";
    	            //添加规格
    	            
    	        }
    	        //如果不存在面料，直接显示材质
    	    }else{
    	        $html.="暂无面料 </div>";
    	        //查询当前单品的材质
    	        $m_list=$crowdItemModel->getMaterialByItem($item_id,0);
    	        $m_count=intval(count($m_list));
    	        if($m_count>0){//存在材质 显示材质，根据材质显示尺寸
    	            $html.="<div class='mabir'><h6> 材质：</h6>";
    	            $m_list=$crowdItemModel->getMaterialByItem($item_id,0);
    	            foreach($m_list as $fari){
    	                $html.=$fari['name']." &nbsp;&nbsp;
	    		<input type='radio' name='CrowdItem[mid]' value='".$fari['mid']."'
	    				            onchange='m_getSite(this)'>";
    	                
    	                $html.="<img  src='".$fari['url']."' width=50px;/>";
    	                $html.="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    	            }
    	            $html.="</div><div class='size'> </div>
    			";
    	        }else{
    	            //没有面料也没有材质的情况，直接显示尺寸   这种情况是不存在的
    	            $html.="<div class='mabir'> <h6> 暂无材质：</h6></div><div class='size'> <h6>暂无尺寸 </h6>";
    	        }
    	        
    	    }
    	}else{
    	    
    	    //没有面料也没有材质的情况，直接显示尺寸   这种情况是不存在的
    	    $html.="暂无面料 </div><div class='mabir'> <h6> 暂无材质：</h6></div><div class='size'> <h6>暂无尺寸 </h6>";
    	}
    	//<input type='button' onclick='checkPrice();'  class='btn btn-success' value='确定规格'/>
    	
    	$html.="

            <div id='del_block'>
                <input type='button' onclick='delCrowedPrice(this);'class='btn btn-success'  value='重新选择'/>
    			
    			 <br/><br/>
            </div
                ";
    	echo $html;exit();
    }
    /**
     * 根据单品id  面料  获取材质  材质onchange为获取尺寸
     */
    public function actionGmlist(){
    	$crowdItemModel=new CrowdItem();
    	$post=Yii::$app->request->post();
    	 $item_id=intval($post['item_id']);
    	 if($item_id==0){
    	 	echo "<div>暂无</div>";exit();
    	 }
    	 $fid=intval($post['fid']);
    	 if($fid==0){
    	 	echo "<div>暂无</div>";exit();
    	 }
    	 $m_list=$crowdItemModel->getMaterialByItem($item_id,$fid);
    	 $html=" <h6> 材质：</h6>"; 
    	 foreach($m_list as $fari){
    	 	$html.=$fari['name']." &nbsp;&nbsp;
	    		<input type='radio' name='CrowdItem[mid]' value='".$fari['mid']."'
	    				            onchange='f_m_getSite(this)'>";
    	 	$html.="<img  src='".$fari['url']."' width=50px;/>";
    	 	$html.=" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    	 }
    	echo $html;exit();
    }
    /**
     *根据item_id fid mid 获取尺寸
     */
    public function actionFmgetsize(){
    	$crowdItemModel=new CrowdItem();
    	$post=Yii::$app->request->post();
         $item_id=intval($post['item_id']);
    	$fid=intval($post['fid']);
    	$mid=intval($post['mid']);     
    	/* $item_id=3;
    	$fid=5;
    	$mid=4; */
    	$sizeList=$crowdItemModel->getSizeByItemFm($item_id,$fid,$mid);
    	if(count($sizeList)==0){
    		//如果没有尺寸  就查找size表
    		$sizeList=$crowdItemModel->getSizeByItem($item_id);
    		if(count($sizeList)>0){
    			$html="<h6> 尺寸：</h6>";
    			foreach($sizeList as $size){
    				$html.=$size['size']."
	    		<input type='radio' name='CrowdItem[size]' value='".$size['id']."'
	    				            onchange='getprice(".$item_id.",".$fid.",".$mid.",".$size['id'].")'>";
    				$html.=" &nbsp;&nbsp;</div><div class='price'>";
    			}
    			echo $html;exit();
    		}else{
    			echo "<h6>暂无尺寸  ";exit();
    		}
    		
    	}else{
    		$html="<h6> 尺寸：</h6>";
    		foreach($sizeList as $size){
    			$html.=$size['size']."
	    		<input type='radio' name='CrowdItem[size]' value='".$size['id']."'
	    				            onchange='getprice(".$item_id.",".$fid.",".$mid.",".$size['id'].")'>";
	    		$html.=" &nbsp;&nbsp;<div class='price'> ";
    		}
    		echo $html;exit();
    	}
    }
    /**
     * 根据item_id  fid 获取尺寸
     */
	public function actionFgetsite(){
		   	$crowdItemModel=new CrowdItem();
		   	$post=Yii::$app->request->post();
		    $item_id=intval($post['item_id']);
		   	$fid=intval($post['fid']); 
		   	$sizeList=$crowdItemModel->getSizeByItemFm($item_id,$fid,0);
		   	if(count($sizeList)==0){
		   		//如果没有尺寸  就查找size表
		   		$sizeList=$crowdItemModel->getSizeByItem($item_id);
		   		if(count($sizeList)>0){
		   			$html="<div class='size'><h6> 尺寸：</h6>";
		   			foreach($sizeList as $size){
		   				$html.=$size['size']."
	    		<input type='radio' name='CrowdItem[size]' value='".$size['id']."'
	    				            onchange='getprice(".$item_id.",".$fid.",0,".$size['id'].")'>";
		   				$html.=" &nbsp;&nbsp;";
		   				$html.="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		   			}
		   			echo $html;exit();
		   		}else{
		   			echo "<div class='size'> <h6>暂无尺寸 </h6>";exit();
		   		}
		   	}else{
		   		$html="<div class='size'><h6> 尺寸：</h6>";
		   		foreach($sizeList as $size){
		   			$html.=$size['size']."
	    		<input type='radio' name='CrowdItem[size]' value='".$size['id']."'
	    				            onchange='getprice(".$item_id.",".$fid.",0,".$size['id'].")'>";
		   			$html.=" &nbsp;&nbsp;</div><div class='price'></div>";
		   		}
		   		echo $html;exit();
		   	}
	   }
	   /**
	    * 根据item_id mid 获取尺寸
	    */
   public function actionMgetsize(){
	   	$crowdItemModel=new CrowdItem();
	   	$post=Yii::$app->request->post();
	 	$item_id=intval($post['item_id']);
	   	$mid=intval($post['mid']);  
	   	$sizeList=$crowdItemModel->getSizeByItemFm($item_id,0,$mid);
	   	if(count($sizeList)==0){
	   		//如果没有尺寸  就查找size表 
	   		$sizeList=$crowdItemModel->getSizeByItem($item_id);
	   		if(count($sizeList)>0){
	   			$html="<div class='size'><h6> 尺寸：</h6>";
	   			foreach($sizeList as $size){
	   				$html.=$size['size']."
	    		<input type='radio' name='CrowdItem[size]' value='".$size['id']."'
	    				            onchange='getprice(".$item_id.",0,".$mid.",".$size['id'].")'>";
	   				$html.=" &nbsp;&nbsp;</div><div class='price'></div>";
	   			}
	   			echo $html;exit();
	   		}else{
	   			echo "<div class='size'> <h6>暂无尺寸 </h6>";exit();
	   		}
	   	}else{
	   		$html="<div class='size'><h6> 尺寸：</h6>";
	   		foreach($sizeList as $size){
	   			$html.=$size['size']." &nbsp;&nbsp;
		    		<input type='radio' name='CrowdItem[size]' value='".$size['id']."'
		    				            onchange='getprice(".$item_id.",0,".$mid.",".$size['id'].")'>";
	   			$html.="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><div class='price'></div>";
	   		}
	   		echo $html;exit();
	   	}
   }
   /**
    * 根据item_id  fid mid 获取价格
    */
   public function actionGetprice(){
   	$crowdItemModel=new CrowdItem();
   	$post=Yii::$app->request->post();
     $item_id=intval($post['item_id']);
   	$mid=intval($post['mid']);
   	$fid=intval($post['fid']);
   	$sid=intval($post['sid']);  
  // 	$item_id=1;$fid=0;$mid=4;$sid=4;
   	$price=$crowdItemModel->getPriceBySize($item_id,$fid,$mid,$sid);
     echo $price;exit();
   }
   public function actionGetpreviewid(){
       $crowdItemModel=new CrowdItem();
       $post=Yii::$app->request->post();
       $item_id=intval($post['item_id']);
       $mid=intval($post['mid']);
       $fid=intval($post['fid']);
       $sid=intval($post['sid']);     
        $crowd_id=intval($post['crowd_id']); 
         /*   $item_id=1;
         $fid= 2;  $mid=0; $sid=0;    $crowd_id=7;   */
       if($item_id==0||($fid==0&&$mid==0)){
           echo 0;exit();
       }
       $preveiwId=$crowdItemModel->checkExitPreview($item_id, $fid, $mid);
       //判断是否已经存在
       $crowdPrice=$crowdItemModel->checkExit($item_id,$crowd_id,$fid,$mid,$sid);
       if(intval($crowdPrice)>0){
           echo 0;exit();
       } 
       if(intval($preveiwId)>0){
           if($sid==0){//如果sid=0  判断prices表 或者     size表是否有size  如果有，不给填充
               $sid=$crowdItemModel->getAllsizeByitem($item_id);
               if(intval($sid)==0){
                   echo $preveiwId;exit();
               }       
           }else{
               echo $preveiwId;exit();
           }
       }else{
           echo 0;exit();
       }
       echo 0;exit(); 
   }
   /**
    * 确定添加,验证数据是否存在
    */
   public function actionCheckprice(){
       	$crowdItemModel=new CrowdItem();
       	$post=Yii::$app->request->post();
         $crowd_id=intval($post['crowd_id']);
        $mid=intval($post['mid']);
       	$fid=intval($post['fid']);
       	$sid=intval($post['sid']); 
       	$item_id=intval($post['item_id']);   
       //	4    1663 0 24  2518 
       //	$item_id=2518;  $crowd_id=4;  $fid=1663; $mid=0;  $sid=24;  
       
       	$previewId=$crowdItemModel->checkExitPreview($item_id, $fid, $mid);
       	if(intval($previewId)==0){
       	    echo -1;exit();//组合不存在
       	}else{
       	    $count=$crowdItemModel->checkExit($item_id,$crowd_id,$fid,$mid,$sid);
       	    if(intval($count)>0){
       	        echo 2;exit();//已存在数据表
       	    }else{
       	        echo $previewId;exit();
       	    }
       	}
   	
   	
   }
   /**
    * 修改规格
    */
   public function actionUpdateprice($id){
   	  $crowdPriceItem=CrowdItemPrice::findOne($id);
   	  $crowdId=$crowdPriceItem->crowd_id;
   	  $crowdItem=CrowdItem::findOne($crowdId);
   	  if ($crowdPriceItem->load(Yii::$app->request->post())) {
   	      $send_time=strtotime($crowdPriceItem->send_time);
   	      $crowdPriceItem->send_time=$send_time;
   	  	$crowdPriceItem->save();
   	  	return $this->redirect(['priceview', 'id' => $crowdPriceItem->id]);
   	  } else {
   	      //反填充页面 面料 材质 尺寸  
   	      $previewId=$crowdPriceItem->preview_id;
   	      if(intval($previewId)>0){
   	          $preview=BaseSysPreview::findOne($previewId);
   	         if(!empty($preview)){
   	             $fid=$preview->fid;
   	             $mid=$preview->mid;
   	         }else{
   	             $previewId=0;
   	             $fid=0;
   	             $mid=0;
   	         }
   	      }else{
   	          $previewId=0;
   	          $fid=0;
   	          $mid=0;
   	      }
   	     
   	      $sid=$crowdPriceItem->size;
   	      $fmsList=$crowdPriceItem->getpreview($previewId,$sid);
   	      $item_id=$crowdItem->item_id;
   	      $price=$crowdItem->getPriceBySize($item_id,$fid,$mid,$sid);
   	    if($crowdPriceItem->send_time==0){
   	          $crowdPriceItem->send_time="";
   	      }else{
   	          $crowdPriceItem->send_time=date("Y-m-d H:i:s",$crowdPriceItem->send_time);
   	      }  
   	  	return $this->render('updateprice', [
   	  			'model' => $crowdPriceItem,
   	  	         'fmsList'=>$fmsList,
   	  	         'fid'=>$fid,
   	  	         'mid'=>$mid,
   	  	         'sid'=>$sid,
   	  	      'item_id'=>$item_id,
   	  	    'crowd_id'=>$crowdId,
   	  	    'price'=>$price
   	  	]);
   	  }
   }
   /**
    * 添加规格
    */
   public function actionAddprice(){
       $crowdPriceItem=new CrowdItemPrice();
       $crowdPriceItem->load(Yii::$app->request->post());
       $crowd_id=$crowdPriceItem->crowd_id;
       $send_time=strtotime( $crowdPriceItem->send_time);
       $crowdPriceItem->send_time=$send_time;
      
       $crowdPriceItem->save();
       return $this->redirect(['update', 'id' => $crowdPriceItem->crowd_id]);
   }
   /**
    * 众筹规格详情页
    */
   public function actionPriceview($id){
   	    $sql="SELECT crowd_price.*,base_sys_fabric.`name` f_name, base_sys_material.`name` m_name,sys_item_size.`size` s_name
			FROM crowd_price 
			LEFT JOIN  base_sys_fabric ON base_sys_fabric.`id` in (SELECT `fid` FROM  base_sys_preview WHERE id=crowd_price.`preview_id`)
			LEFT JOIN  base_sys_material ON base_sys_material.`id` in (SELECT `mid` FROM  base_sys_preview WHERE id=crowd_price.`preview_id`)
			LEFT JOIN  sys_item_size ON sys_item_size.`id`=crowd_price.`size`
			WHERE crowd_price.id=:id";
   	    $param=array(":id"=>$id);
   		$model = CrowdItemPrice::findBySql($sql,$param)->One();
    	return $this->render('priceview', [
    			'model' => $model
    	]);
   }
   /**
    * 进行添加
    */
   public function  actionAdditemprice(){
       	$crowdItemModel=new CrowdItem();
       	$post=Yii::$app->request->post();
        $crowd_id=intval($post['crowd_id']);	
        $mid=intval($post['mid']);
       	$fid=intval($post['fid']);
       	$sid=intval($post['sid']);
       	$item_id=intval($post['item_id']);  
       	$price=$post['price'];   
       	
       	$exceed_limit=$post['exceed_limit'];
       	$order_count=$post['order_count'];
       	$price_limit=$post['price_limit'];
       	$send_time=$post['send_time'];
       	$send_time=strtotime($send_time);
    /*    	
       	$crowd_id=3;
       	$fid=1663;
       	$sid=0;
       	$mid=0;
       	$item_id=2727; */
       	if($price<=0){
       		echo 3;exit();
       	}
       	//判断是否存在这个组合
       	$previewId=$crowdItemModel->checkExitPreview($item_id, $fid, $mid);
       	if($previewId>0){
       	    $count=$crowdItemModel->checkExit($item_id,$crowd_id,$fid,$mid,$sid);
       	    if(intval($count)>0){
       	        echo 2;exit();//规格已存在
       	    }else{
       	        $crowdItemPriceModel=new CrowdItemPrice();
       	        $crowdItemPriceModel->crowd_id=$crowd_id;
       	        $crowdItemPriceModel->size=$sid;
       	        $crowdItemPriceModel->price=$price;
       	        $crowdItemPriceModel->preview_id=$previewId;
       	        $crowdItemPriceModel->exceed_limit=$exceed_limit;
       	        $crowdItemPriceModel->order_count=$order_count;
       	        $crowdItemPriceModel->price_limit=$price_limit;
       	        $crowdItemPriceModel->send_time=$send_time;
       	        $result=$crowdItemPriceModel->save();
       	        echo $result;exit();
       	    }
       	}else{
       	    echo 5;exit();//组合不存在
       	}
       	
   }
    /**
     * 查看单条数据
     */
    public function actionView($id){
    	$this->layout = 'main_small';
    	$sql="   SELECT crowd_item.*,sys_item.name item, sys_image.url  item_url,c_image.url  crowd_url  FROM crowd_item 
                  LEFT JOIN sys_item ON sys_item.id=crowd_item.`item_id`
                  LEFT JOIN sys_image ON sys_image.`id`=sys_item.`img_thumb_id`
                  left join sys_image c_image on c_image.id=crowd_item.img_crowd_id
                  WHERE crowd_item.id=:crowd_id";
    	$param=array(":crowd_id"=>$id);
    	$model = CrowdItem::findBySql($sql,$param)->One();
    	$crowItemPriceModel=new CrowdItemPrice();
    	$Crowd=CrowdItem::findOne($id);
    	$item_id=$Crowd->item_id;
    	$crowpriceList=$crowItemPriceModel->getPriceByCrowdid($id);
    	//查询用户类型
    	$user_types=$model->user_types;
    	if($user_types==""){
    	    $user_Str="所有用户";
    	}else{
    	    $crowdItem=new CrowdItem();
    	    $user_Str=$crowdItem->getUsertypeStrById($user_types);
    	}
    	$model->user_types=$user_Str;
    	return $this->render('view', [
    	    'model' => $model,
    	    'dataProvider' =>$crowpriceList,
    	    'searchModel'=>$crowItemPriceModel,
    	    'crowId' => $id,
    	    'item_id'=>$item_id,
    	]);
    }
   /**
    * 众筹退款列表
    */
    public function actionRefund(){
        //查询所有众筹失败的众筹列表 -- 根据某个众筹点击进入众筹退款详情
        $searchModel = new CrowdItemSearch();
        $dataProvider = $searchModel->crwodrefundsearch(Yii::$app->request->queryParams);
        return $this->render('crowd_refund', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
   
    public function actionCrowdRefund($id){
        $searchModel = new CrowdItemSearch();
        $dataProvider = $searchModel->refundsearch(Yii::$app->request->queryParams,$id);
        return $this->render('refund_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    
  /**
     * 退款
     */
    public function actionCheckRefund(){
        //判断当前用户是否有退款权限
        if(!Yii::$app->user->can('crowd-refund')){
            throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
        }
        $post=Yii::$app->request->post();
        $Crowd_item=new CrowdItem();
        $idlist=$post['ids'];
        $count=count($idlist);
        $return_result=array("code"=>'1',"msg"=>'退款成功');
        if($count>1){
            //批量退款
            for($i=0;$i<$count;$i++){
                $id=$idlist[$i];
                $payTrade=PayTrade::findOne($id);
                $trade_no=$payTrade['trade_no'];
                $trade_id=$payTrade['id'];
                $item_price_id=$payTrade['crowd_price_id'];
                $crowd_item=CrowdItemPrice::findOne($item_price_id);
                $crowd_item_id=$crowd_item['crowd_id'];
                $type=0;
                $transaction_id="";
                $price_modify=$payTrade["price_modify"];
                if($trade_no!=""){
                    $log_pay=LogPay::findOne(['trade_no'=>$trade_no]);
                    $type=intval($log_pay->type);
                    $transaction_id=$log_pay->transaction_id;
                }
                switch ($type){
                    case 1://微信支付
                        $starttime=time();
                        $result=$this->actionWechatRefund($transaction_id, $price_modify);
                        $result=json_decode($result);
                        $result=(array)$result;
                        if(intval($result['code'])==1){
                            $this->logrefundSave($result['out_refund_no'], "众筹失败微信退款", $transaction_id, $trade_no, $payTrade['user_id'], 1, $starttime, $result['xml'], $price_modify, 20);
                            $this->updatePayTradeState($trade_id);
                            //查询该众筹还有没有待退款订单，如果全部退款，修改众筹state=5
                            $ifexit=$Crowd_item->checkExitRufund($crowd_item_id);
                            if(!$ifexit){
                                $this->updateCrowdItemState($crowd_item_id);
                            }
                        }else{
                            $this->logrefundSave("", "众筹失败微信退款-".$result['msg'], $transaction_id, $trade_no, $payTrade['user_id'], 1, $starttime, $result['xml'], $price_modify, 30);
                            $return_result=array("code"=>'2',"msg"=>$result['msg']);
                        }
                        break;
                    case 2://支付宝支付
                        $param=array();
                        $starttime=time();
                        $param['out_biz_no']=$trade_no;//商户订单号
                        $lenght=strlen($transaction_id);
                        $transaction_id=substr($transaction_id, 4,28);
                        $param['trade_no']=$transaction_id;//支付宝交易号
                        $param['payee_account']=$price_modify;;
                        $result=$this->actionAlipayRefund($param);
                        $result=json_decode($result);
                        $result=(array)$result;
                        $xml = "无";
                        $code=$result['code'];
                        $msg=$result['msg'];
                        if($code=="10000"){//转账成功
                            $this->logrefundSave($result['out_trade_no'], "众筹失败支付宝退款", $transaction_id, $trade_no, $payTrade['user_id'], 2, $starttime, $xml, $price_modify, 20);
                            $this->updatePayTradeState($trade_id);
                            $ifexit=$Crowd_item->checkExitRufund($crowd_item_id);
                            if(!$ifexit){
                                $this->updateCrowdItemState($crowd_item_id);
                            }
                        }else{
                            $this->logrefundSave("", "众筹失败支付宝退款-".$result['msg'], $transaction_id, $trade_no, $payTrade['user_id'], 2, $starttime, $xml, $price_modify, 30);
                            $return_result=array("code"=>'2',"msg"=>$result['msg']);
                        }
                        break;
                }
            }
        }else{
            //单条退款
            $id=$idlist[0];
            //根据log_pay判断支付类型
            $payTrade=PayTrade::findOne($id);
            $trade_no=$payTrade['trade_no'];
            $trade_id=$payTrade['id'];
            $item_price_id=$payTrade['crowd_price_id'];
            $crowd_item=CrowdItemPrice::findOne($item_price_id);
            $crowd_item_id=$crowd_item['crowd_id'];
            $type=0;
            $transaction_id="";
            $price_modify=$payTrade["price_modify"];
            if($trade_no!=""){
                $log_pay=LogPay::findOne(['trade_no'=>$trade_no]);
                $type=intval($log_pay->type);
                $transaction_id=$log_pay->transaction_id;
            }
            switch ($type){
                case 1://微信支付
                    $starttime=time();
                    $result=$this->actionWechatRefund($transaction_id, $price_modify);
                    $result=json_decode($result);
                    $result=(array)$result;
                    if(intval($result['code'])==1){
                        $this->logrefundSave($result['out_refund_no'], "众筹失败微信退款", $transaction_id, $trade_no, $payTrade['user_id'], 1, $starttime, $result['xml'], $price_modify, 20);
                        $this->updatePayTradeState($trade_id);
                        $ifexit=$Crowd_item->checkExitRufund($crowd_item_id);
                        if(!$ifexit){
                            $this->updateCrowdItemState($crowd_item_id);
                        }
                    }else{
                        $this->logrefundSave("", "众筹失败微信退款-".$result['msg'], $transaction_id, $trade_no, $payTrade['user_id'], 1, $starttime, $result['xml'], $price_modify, 30);
                        $return_result=array("code"=>'2',"msg"=>$result['msg']);
                    }
                    break;
                case 2://支付宝支付
                    $starttime=time();
                    $transaction_id=substr($transaction_id, 4,28);
                    $param=array("out_biz_no"=>$trade_no,"trade_no"=>$transaction_id,"payee_account"=>$price_modify);
                    $result=$this->actionAlipayRefund($param);
                    $result=json_decode($result);
                    $result=(array)$result;
                    
                    $xml = "无";
                    $code=$result['code'];
                    $msg=$result['msg']; 
                     if($code=="10000"){//转账成功
                         $this->logrefundSave($result['out_trade_no'], "众筹失败支付宝退款", $transaction_id, $trade_no, $payTrade['user_id'], 2, $starttime, $xml, $price_modify, 20);
                         $this->updatePayTradeState($trade_id);
                         $ifexit=$Crowd_item->checkExitRufund($crowd_item_id);
                         if(!$ifexit){
                            $this->updateCrowdItemState($crowd_item_id);
                         }
                     }else{
                         $this->logrefundSave("","众筹失败支付宝退款-".$result['msg'], $transaction_id, $trade_no, $payTrade['user_id'],2, $starttime, $xml, $price_modify,30);
                         $return_result=array("code"=>'2',"msg"=>$result['msg']);
                     }
                    break;
            }
           
        }
        echo json_encode($return_result);exit();
    }
    /**
     * 当前众筹所有订单退款完成，修改众筹状态state=5
     */
    public function updateCrowdItemState($crowd_item_id){
        $Crowd=CrowdItem::findOne($crowd_item_id);
        $Crowd['state']=5;
        $Crowd->save();
    }
    /**
     * 退款完成，修改订单表状态  price_state=3 trade_state=5
     */
    public function updatePayTradeState($trade_id){
        $old_payTrade=PayTrade::findOne($trade_id);
        $old_payTrade['trade_state']=2;//交易关闭
        $old_payTrade['price_state']=3;
        $old_payTrade->save();
        //修改PayLogistics
        $payLogistics=PayLogistics::find()->where("trade_id={$trade_id}")->one();
        $payLogistics['logistics_state']=3;
        $payLogistics->save();
    }
    /**
     * 添加logrefund表
     * @param   $third_refund_no
     * @param   $msg
     * @param   $transaction_id
     * @param   $trade_no
     * @param   $user_id
     * @param   $type
     * @param   $starttime
     * @param   $xml
     * @param   $price_modify
     * @param   $state
     */
    public function  logrefundSave($third_refund_no,$msg,$transaction_id,$trade_no,$user_id,$type,$starttime,$xml,$price_modify,$state){
        $refund=new LogRefund();
        $refund['refund_no']=time().rand(1,100);
        $refund['third_refund_no']=$third_refund_no;
        $refund['done_list']=$msg;
        $refund['transaction_id']=$transaction_id;
        $refund['trade_no']=$trade_no;
        $refund['uid']=$user_id;
        $refund['type']=$type;//1 - 微信 2 - 支付宝
        $refund['starttime']=$starttime;
        $refund['endtime']=time();
        $refund['memo_xml']=$xml;
        $refund['rmb']=$price_modify;
        $refund['state']=$state;
        $refund['state_count']=1;
        $refund['addtime']=time();
        $refund['type_class']=1;
        $refund->save();
    }
    /**
     * 微信退款 
     *  out_refund_no  商户系统内部的退款单号，商户系统内部唯一，只能是数字、大小写字母_-|*@ ，同一退款单号多次请求只退一笔。
     *   $transaction_id  微信生成的订单号
     */
    public function actionWechatRefund($transaction_id,$amount){
        $amount = doubleval($amount)* 100;//单位  分
        $package['appid'] = Yii::$app->params['weixin']['WX_APPID'];
        $package['mch_id'] =  Yii::$app->params['weixin']['WX_MCHID'];
        $package['nonce_str'] =  PayRebateUsertake::getRandChar(15);
        $package['transaction_id']=$transaction_id;
        $package['out_refund_no']=Yii::$app->params['weixin']['WX_MCHID'].date("YmdHis").rand(0,100);
        $package['total_fee'] = $amount;
        $package['refund_fee']=$amount;
        $package =PayRebateUsertake::secretkeyAction($package);
        $dat = PayRebateUsertake::array2xml($package);
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
        $responseXml = PayRebateUsertake::curl_post_ssl($url, $dat);
        $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $responseArr = (array)$responseObj;
        //企业支付出错
        $Xml = PayRebateUsertake::array2xml($responseArr);
        $payresult=json_encode(array("code"=>2,'msg'=>$responseArr['return_msg'],"xml"=>$Xml));
        if ($responseArr['return_code'] == 'FAIL') {
            $payresult= json_encode(array("code"=>2,"msg"=>"FAIL:".$responseArr['return_msg'],"xml"=>$Xml ));
        }elseif($responseArr['return_code'] == 'SUCCESS'){
            if($responseArr['result_code']=="FAIL"){
                $payresult=json_encode(array("code"=>2,"msg"=>$responseArr['err_code_des'],"xml"=>$Xml ));
            }else{
                $payresult=json_encode(array("code"=>1,"msg"=>"支付成功","out_refund_no"=>$responseArr['refund_id'],"refund_fee"=>$responseArr['refund_fee'],"xml"=>$Xml
                ));
            }
        }
        /**
         * 成功
         * Array ( [return_code] => SUCCESS [return_msg] => OK [appid] => wx865a0f13acf4bc81 
         * [mch_id] => 1304926501 [nonce_str] => MAZDljxsj7b2FHWD [sign] => 99506DC52FC59F1EDF63514D320F2991
         *  [result_code] => SUCCESS [transaction_id] => 4200000115201807172675333005
         *   [out_trade_no] => 733420091531806996_1_40 [out_refund_no] => 13049265012018071714592383
         *    [refund_id] => 50000507562018071705480399323 [refund_channel] => stdClass Object ( ) 
         *    [refund_fee] => 1 [coupon_refund_fee] => 0 [total_fee] => 1 [cash_fee] => 1
         *     [coupon_refund_count] => 0 [cash_refund_fee] => 1 )
         */
         /**
          * 失败
          * Array ( [return_code] => SUCCESS [return_msg] => OK [appid] => wx865a0f13acf4bc81
          *  [mch_id] => 1304926501 [nonce_str] => EishQa028OfoPGHM [sign] => 8AB423E572446E586F4DEC912639540F 
          *  [result_code] => FAIL [err_code] => ERROR [err_code_des] => 订单已全额退款 )
          */
        return $payresult;
    }
   /**
    * 支付宝退款
    */
    public function actionAlipayRefund($param){
        $config=array();
        $config['appId']=Yii::$app->params['alipay']['appid'];
        $config['rsaPrivateKey']=Yii::$app->params['alipay']['rsaPrivateKey'];
        $config['alipayrsaPublicKey']=Yii::$app->params['alipay']['alipayrsaPublicKey'];
        
        $out_biz_no=$param['out_biz_no'];//商户订单号
        $trade_no=$param['trade_no'];//支付宝交易号
        $refund_amount=$param['payee_account'];
        
        $makemoneyApi=new makemoneyApi();
        $responseObj= makemoneyApi::refund($config, $param);
        $responseArray=json_decode($responseObj);
        $responseArray=(array)$responseArray;
        return  json_encode($responseArray);
    }
    /**
     * 查找单个
     * @param   $id
     * @throws NotFoundHttpException
     */
    protected function findModel($id)
    {
        if (($model = CrowdItem::findOne($id)) !== null) {
        	$model = CrowdItem::find()->where('id='.$id)->one();
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    protected  function findPriceModel($id){
    	if (($model = CrowdItemPrice::findOne($id)) !== null) {
    		$model = CrowdItemPrice::find()->where('id='.$id)->one();
    		return $model;
    	} else {
    		throw new NotFoundHttpException('The requested page does not exist.');
    	}
    }
    /**
     * (non-PHPdoc)
     * @see \yii\base\Controller::actions()
     * by suiyue
     */
    public function actions(){
    	return [
    			'upload'=>[
    					'class'=>'backend\widgets\ueditor\UEditorAction',
    					'config'=>[
    							//  /gjj/backend/web/images/
    							'imageUrlPrefix'=>"https://".$_SERVER['SERVER_NAME']."/gjj/backend/web/images/",//图片访问路径前缀
    							'imagePathFormat'=>'{rand:2}/{time}{rand:6}',
    							'imageRoot'=>\Yii::getAlias("images")
    					]
    			]
    	];
    
    }

    /**
     * 删除
     */
    public function actionDelete(){
    	
    }

}
 